#include "SymmetricKey.h"

namespace kryptos { namespace cryptography {

SymmetricKey::SymmetricKey(bool reuseWhenFinished)
    : m_reuse(reuseWhenFinished)
    , m_offset(0)
{
}

SymmetricKey::~SymmetricKey()
{

}

void SymmetricKey::setOffset(unsigned long long len)
{
    m_offset = len;
}

void SymmetricKey::goBack(unsigned long long len)
{
    if (m_reuse)
    {
        // if key is reusable, moving back anf forth is like
        // moving in a ring. When passing back 0, it should start from the end
        // moving back 7 positions from offset 3, would end up in offset 6
        long long aux = m_offset - len;
        m_offset = (aux < 0) ? m_size + aux : aux;
    }
    else
    {
        m_offset = (len < m_offset) ? m_offset - len
                                    : 0;
    }
}

void SymmetricKey::goForward(unsigned long long len)
{
    if (m_reuse)
    {
        // if key is reusable, moving back anf forth is like
        // moving in a ring. When passing through the end, it should start from the begining
        // moving forward 8 positions from offset 3, would end up in offset 1
        long long left = m_size - m_offset;
        m_offset = (left > len) ? m_offset + len : len - left;
    }
    else
    {
        m_offset = (len <  m_size - m_offset) ? m_offset + len
                                    : 0;
    }
}

void SymmetricKey::reset()
{
    m_offset = 0;
}

std::string SymmetricKey::id()
{
    return m_id;
}

unsigned long long SymmetricKey::offset()
{
    return m_offset;
}

unsigned long long SymmetricKey::size()
{
    return m_size;
}

}}
